<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm"/>
  </BasicModal>
</template>

<script setup lang="ts">
import {computed, ref, unref} from 'vue';
import {formSchema} from './org.data';
import {useMessage} from '@/hooks/web/useMessage';
import {getOrgApi, addOrgApi, editOrgApi, getOrgNoApi} from '@/api/core/org.api';
import {BasicModal, useModalInner} from '@/components/Modal';
import {BasicForm, useForm} from '@/components/Form';
import {listDeptApi} from "@/api/system/organize/dept.api";

const emit = defineEmits(['success', 'register']);
const {createMessage} = useMessage();
const isUpdate = ref(true);

const [registerForm, {updateSchema,resetFields, setFieldsValue, validate}] = useForm({
  labelWidth: 80,
  schemas: formSchema,
  showActionButtonGroup: false,
});

const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  resetFields();
  setModalProps({confirmLoading: false});
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    const org = await getOrgApi(data.record.id);
    setFieldsValue({...org});
  } else {
    const org = await getOrgNoApi();
    setFieldsValue({"orgNo": org.orgNo});
  }
  const treeData = await listDeptApi({
    id: unref(isUpdate) ? data.record.id : undefined,
    defaultNode: true,
    exNodes: unref(isUpdate),
  });
  updateSchema({ field: 'areaId', componentProps: { treeData } });
});

/** 标题初始化 */
const getTitle = computed(() => (!unref(isUpdate) ? '新增信息管理' : '编辑信息管理'));

/** 提交按钮 */
async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({confirmLoading: true});
    unref(isUpdate)
      ? await editOrgApi(values).then(() => {
        closeModal();
        createMessage.success('编辑信息管理成功！');
      })
      : await addOrgApi(values).then(() => {
        closeModal();
        createMessage.success('新增信息管理成功！');
      });
    emit('success');
  } finally {
    setModalProps({confirmLoading: false});
  }
}
</script>
